package com.csu54sher.basereservation.Interceptor;

import com.csu54sher.basereservation.properties.JWTproperties;
import com.csu54sher.basereservation.util.JWTUtil;
import com.csu54sher.basereservation.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private JWTproperties jwtProperties;

    /**
     * JWT 拦截器
     * 拦截除 /login 和 /register 外的请求，校验 JWT 合法性
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        log.debug("请求详情 - URI: {}, Method: {}, Handler: {}", requestURI, method, handler.getClass().getName());

        // 0. 非 Controller 方法（例如静态资源）直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 1. 获取请求路径


        // 2. 排除登录和注册接口（大小写安全）
        if (requestURI.equalsIgnoreCase("/login") || requestURI.equalsIgnoreCase("/register")) {
            log.debug("跳过 JWT 校验接口：{}", requestURI);
            return true;
        }

        // 3. 从请求头中获取 Token
        String token = request.getHeader(jwtProperties.getTokenName());

        // 4. 校验 Token
        try {
            log.info("JWT 校验开始, token={}", token);
            String idNumber = JWTUtil.getIdNumber(token, jwtProperties.getSecretKey());
            log.info("✅ JWT 校验通过, 当前用户学号：{}", idNumber);
            //将当前用户的学号或者工号存入threadlocal
            ThreadLocalUtil.setCurrentId(idNumber);
            return true; // 通过放行
        } catch (Exception e) {
            log.error("❌ JWT 校验失败: {}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
            return false;
        }
    }
}
